/**
 * 框架入口
 * Copyright(c) purenode
 * @author yangjian102621@gmail.com
 * MIT Licensed
 */

"use strict";

var server = require("./server.js");
var router = require("./router.js").Router;
var _configs = require("../configs.js");
var mysql = require("mysql");

exports = module.exports = createApplication;

function createApplication() {
	var app = {

		configs : {}, //配置信息

		_DB : null, //数据库连接

		staticPath : {}, //静态资源路径

		//初始化
		init : function() {
			this.configs = _configs;
			
			//初始化数据库配置
			var configs = this.configs["DB_CFG"];	
			this._DB = mysql.createConnection({
				host: configs.host,
				user: configs.user,
				password: configs.pass,
				database: configs.database,
				port: configs.port
			});
			this._DB.connect();

		},

		//添加静态资源目录
		static : function(filePath) {
			this.staticPath[filePath] = 1;
		},

		listen : function(port) {
			server.start(router, port, app);
		},

		//添加，修改配置参数
		config : function(key, value) {
			this.configs[key] = value;
		},

		//重置配置参数
		setConfigs : function(conf) {
			this.configs = conf;
		},

		//获取全部配置参数
		getConfigs : function() {
			return this.configs;
		},

		//获取指定的配置参数
		getConfig : function(key) {
			return this.configs[key];
		},

		getDB : function() {
		
			return this._DB;
		},

		//发送404请求页面
		page404 : function(res) {
			res.writeHead(404, {"Content-Type" : "text/html"});
			res.write("<h1>404 Not Found.</h1>");
			res.end();
		},

		//设置module, action, method
		getModule : function() {
			return this.module;
		},

		setModule : function(module) {
			this.module = module;
		},

		getAction : function() { 
			return this.action;
		},

		setAction : function(action) {
			this.action = action;
		},

		getMethod : function() {
			return this.method;
		},

		setMethod : function(method) {
			this.method = method;
		}


		
	};

	//初始化应用
	app.init();

	return app;
}

//捕获运行时异常，防止抛出异常使服务器崩溃
if ( DEBUG == false ) {
	process.on('uncaughtException', function (err) {
		console.log('Caught exception: ' + err);
	});
}

exports = module.exports = createApplication;

